local M = {}
local search_dirs = {}

-- 加载目录列表
function M.load_dirs()
  local cwd = vim.fn.getcwd()
  local json_path = cwd .. "/.telescope_dirs.json"
  local file = io.open(json_path, "r")

  if not file then
    return {}
  end

  local content = file:read("*a")
  file:close()

  local ok, decoded = pcall(vim.json.decode, content)
  if not ok or type(decoded) ~= "table" then
    vim.notify("Failed to parse telescope_dirs.json in " .. cwd, vim.log.levels.ERROR)
    return {}
  end

  for i, dir in ipairs(decoded) do
    decoded[i] = vim.fn.fnamemodify(vim.fn.expand(dir), ":p")
  end

  return decoded
end

-- 智能搜索：自动在所有配置目录中搜索
function M.smart_live_grep()
  local dirs = M.load_dirs()
  local cwd = vim.fn.getcwd()
  table.insert(dirs, 1, cwd) -- 把当前目录插入到最前面

  if #dirs == 0 then
    vim.notify("No directories to search in", vim.log.levels.WARN)
    return
  end

  require("telescope.builtin").live_grep({
    search_dirs = dirs,
    prompt_title = "Live Grep in Multiple Dirs",
    path_display = { "smart" },
  })
end

-- 智能查找文件
function M.smart_find_files()
  local dirs = M.load_dirs()
  if #dirs == 0 then
    vim.notify("No directories to search in", vim.log.levels.WARN)
    return
  end

  require("telescope.builtin").find_files({
    search_dirs = dirs,
    prompt_title = "Find Files in Multiple Dirs",
  })
end

-- 手动选择目录搜索（带 <C-f> 切换）
local function try_with_fallback(telescope_fn, prompt_text)
  local cwd = vim.fn.getcwd()

  telescope_fn({
    cwd = cwd,
    attach_mappings = function(_, map)
      map("i", "<C-f>", function()
        local dirs = search_dirs or M.load_dirs()
        if not dirs or #dirs == 0 then
          vim.notify("No fallback search dirs found", vim.log.levels.WARN)
          return
        end

        vim.ui.select(dirs, { prompt = prompt_text }, function(choice)
          if choice then
            local absolute_choice = vim.fn.fnamemodify(choice, ":p")
            telescope_fn({ cwd = absolute_choice })
          end
        end)
      end)
      return true
    end
  })
end

function M.fallback_find_files()
  try_with_fallback(require("telescope.builtin").find_files, "Fallback: Find Files in...")
end

function M.fallback_live_grep()
  try_with_fallback(require("telescope.builtin").live_grep, "Fallback: Live Grep in...")
end

function M.reload()
  search_dirs = M.load_dirs()
  vim.notify("Reloaded telescope_dirs.json", vim.log.levels.INFO)
end

function M.setup()
  search_dirs = M.load_dirs()

  vim.api.nvim_create_user_command("TelescopeSmartGrep", M.smart_live_grep, {})
  vim.api.nvim_create_user_command("TelescopeSmartFind", M.smart_find_files, {})
  vim.api.nvim_create_user_command("TelescopeGrepInDirs", M.fallback_live_grep, {})
  vim.api.nvim_create_user_command("TelescopeFindInDirs", M.fallback_find_files, {})
  vim.api.nvim_create_user_command("ReloadSearchDirs", M.reload, {})
end

return M

